#!/usr/bin/env python

import sys, os, sqlite3, fileinput
DB_FILE = 'quiz.sqlite'
IMPORT_FROM = 'import.txt'
GET_QUESTION = 1
GET_CHOICES = 2
GET_RIGHTANSWER = 3
GET_SCORE = 4

def main():
    conn = sqlite3.connect(DB_FILE)
    conn.row_factory = sqlite3.Row
    cur = conn.cursor()
    status = GET_QUESTION
    for line in fileinput.input(IMPORT_FROM, openhook=fileinput.hook_encoded("utf-8")):
        if line.startswith(u'\ufeff'):
            line = line[1:]
            print 'yes, BOM'
            print line
        if status == GET_QUESTION:
            question = line.rstrip('\r\n')
            status = GET_CHOICES
        elif status == GET_CHOICES:
            choices = line.rstrip('\r\n')
            status = GET_RIGHTANSWER
        elif status == GET_RIGHTANSWER:
            answer = line.rstrip('\r\n')
            status = GET_SCORE
        elif status == GET_SCORE:
            score = int(line)
            cur.execute('''insert into dragon_quiz (question, choices, right_answers, score) 
                    values('%s', '%s', '%s', '%d')
                    '''% (question, choices, answer, score))
            conn.commit()
            status = GET_QUESTION
    else:
        print 'end collecting'

    cur.close()


if __name__ == '__main__':
    main()
